#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import tornado.ioloop
import tornado.web
import tornado.options
import tornado.escape
import tornado.httpserver
from views import guest, app_api, img_api, user_api, card_api, city_api, \
    city_update_api, sight_api, topic_api, topic_note_api, \
    weixin, activity, mobile_web, user_buddy_api, message_api,\
    user_feed_api, user_buddy_feed_api, shout_api, feedback_api,\
    prov_api

from controls import mongo
from utils import log
from config import etc
from views.cms import manage_web, manage_web2, manage_note_api, manage_topic_api, \
    manage_user_api, manage_fake_user_api, manage_feedback_api, manage_gallery_api, manager_api, \
    manage_message_api

class Application(tornado.web.Application):
    def __init__(self):
        settings = dict(
            template_path=etc.path_template,
            static_path=etc.path_static,
            cookie_secret=etc.cookie_secret,
            login_url=r"guest",
            xsrf_cookies=False,
        )
        handlers = [

            # 网站
            (r"/", guest.MainHandler),
            (r"/index", guest.MainHandler),
            (r"/app/qmap/([a-z]+)", guest.AppQmapHandler),
            (r'/web/signin', mobile_web.WebSigninHandler),  # 用户登录
            (r'/web/bind/phone', mobile_web.WebBindPhoneHandler),  # 绑定手机
            (r'/web/topic/list', mobile_web.WebTopicListHandler),  # 话题列表
            (r'/web/note/list', mobile_web.WebNoteListHandler),  # 话题Note
            (r'/web/note/post', mobile_web.WebNotePostHandler),  # 发新话题
            (r'/web/findpwd', mobile_web.WebFindPwdHandler),  # 找回密码
            (r'/web/topic/top', mobile_web.TopicTopNoteListHandler),

            # 微信
            (r"/weixin/cgi", weixin.CgiHandler),
            (r"/weixin/home", weixin.HomeHandler),
            (r"/weixin/web/callback", weixin.WebCallbackHandler),
            (r'/weixin/web/signin/redirect', tornado.web.RedirectHandler,
             {"url": etc.WX_SIGNIN_REDIRECT, "permanent": True}),

            # 活动
            (r"/activity/20150701/horoscope", activity.HoroscopeHandler),
            (r"/activity/20150701/horesult/([0-9]+)/([a-zA-Z]+)", activity.HoResultHander),

            # app版本号
            (r"/api/app/getnewver", app_api.NewVerHandler),  # 2.1.0 deprecated from 2.2.0
            (r"/api/app/newver", app_api.NewVerHandler),  # 2.2.0

            (r"/api/prov/list", prov_api.ListHandler),

            # 城市接口
            (r"/api/city/getcards", city_api.GetCardsHandler),  # 2.1.0
            (r"/api/city/product", city_api.ProductHandler),  # 2.1.0
            (r"/api/city/list", city_api.ListHandler),  # 2.1.0
            (r"/api/city/mappath", city_api.GetMapVerHandler),  # 2.1.0 deprecated from 2.2.0
            (r"/api/city/getmapver", city_api.GetMapVerHandler),  # 2.2.0
            (r"/api/city/sights", city_api.SightsHandler),  # 2.1.0 deprecated from 2.2.0

            # 景点接口
            (r"/api/sight/dict", sight_api.DictHandler),  # 2.1.0
            (r"/api/sight/detail", sight_api.SightDetailHandler),  # 2.1.0
            (r"/api/sight/desc", sight_api.SightDescTitleHandler),  # 2.1.0
            (r"/api/sight/getcomment", sight_api.GetCommentHandler),  # 2.1.0
            (r"/api/sight/addcomment", sight_api.AddCommentHandler),  # 2.1.0

            # 卡牌接口
            (r"/api/card/getcomment", card_api.GetCommentHandler),  # 2.2.0
            (r"/api/card/addcomment", card_api.AddCommentHandler),  # 2.2.0
            (r"/api/card/collect", card_api.CollectHandler),  # 2.2.0
            (r"/api/card/getcollcount", card_api.GetCollectCountHandler),  # 2.2.0

            # 个人中心接口
            (r"/api/user/signin", user_api.SignInHandler),      # 2.3.0
            (r"/api/user/signout", user_api.SignOutHandler),    # 2.3.0
            (r"/api/user/validate", user_api.ValidateHandler),
            (r"/api/user/signup", user_api.SignUpHandler),      # 2.3.0
            (r"/api/user/findpwdverify", user_api.FindPwdVerifyHandler),  # 2.3.0
            (r"/api/user/resetpwd", user_api.ResetPwdHandler),  # 2.3.0
            (r"/api/user/pwdedit", user_api.PwdEditHandler),    # 2.3.0
            (r"/api/user/getuser"           , user_api.GetUserHandler),
            (r'/api/user/sendsms',  user_api.SendCodeHandler),      # 发送短信
            (r'/api/user/my_notes', user_api.MyPostNotesHandler),   # 我发表的note
            (r'/api/user/my_likes', user_api.MyLikeNotesHandler),   # 我的点赞
            (r'/api/user/updatedetail'      , user_api.UpdateUserDetailHandler),
            (r'/api/user/updatebrief'       , user_api.UpdateUserBriefHandler),

            # 自己动态
            (r'/api/user/feed/list', user_feed_api.FeedListHandler),
            (r'/api/user/feed/hide/set', user_feed_api.FeedHideSetHandler),
            (r'/api/user/feed/buddy', user_buddy_feed_api.GetBuddyFeedHandler),

            # 喊话
            (r'/api/shout/list', shout_api.ShoutListHandler),
            (r'/api/shout/update', shout_api.ShoutUpdateHandler),

            # 用户关系接口
            (r'/api/user/follow'            , user_buddy_api.FollowHandler),
            (r'/api/user/unfollow'          , user_buddy_api.UnfollowHandler),
            (r'/api/user/getfollow'         , user_buddy_api.GetFollowHandler),
            (r'/api/user/getfans'           , user_buddy_api.GetFansHandler),
            (r'/api/user/getbuddycount'     , user_buddy_api.GetBuddyCountHandler),
            (r'/api/user/square'            , user_buddy_api.GetSquare),
            (r'/api/user/buddy/type'        , user_buddy_api.GetBuddyTypeHandler),

            #话题接口
            (r'/api/topic/list'             , topic_api.ListHandler),
            (r'/api/topic/hot'              , topic_api.HotHandler),              # 精选主题
            (r'/api/topic/like/post'        , topic_api.LikeTopicHandler),
            (r'/api/topic/like/del'         , topic_api.DelTopicLikeHandler),
            (r'/api/topic/one'              , topic_api.ListOneHandler),

            #Note接口
            (r'/api/note/list'              , topic_note_api.ListHandler),
            (r'/api/note/post'              , topic_note_api.PostHandler),
            (r'/api/note/like/post'         , topic_note_api.LikePostHandler),
            (r'/api/note/like/del'          , topic_note_api.DelPostLikeHandler),
            (r'/api/note/one', topic_note_api.ListOneHandler),

            # message接口
            (r'/api/message/system', message_api.ListSystemMessageHandler),
            (r'/api/message/system/del', message_api.DelAllSystemMessageHandler),
            (r'/api/message/user', message_api.UserMessageHandler),
            (r'/api/message/user/add', message_api.UserMessageAddHandler),
            (r'/api/message/user/del', message_api.UserMessageDelHandler),
            (r'/api/message/pet', message_api.PetMessageHandler),
            (r'/api/message/pet/add', message_api.PetMessageAddHandler),
            (r'/api/message/pet/del', message_api.PetMessageDelHandler),
            (r'/api/message/note/like', message_api.NoteLikeHandler),

            (r'/api/feedback/add', feedback_api.FeedbackAddHandler),

            # #游记接口
            # (r"/api/journey/collect"        , journey_collect_api.CollectHandler),# 未启用
            # (r"/api/journey/browse"         , journey_browse_api.BrowseHandler),# 未启用
            # (r"/api/journey/browsesight"    , journey_browse_api.BrowseSightHandler),# 未启用
            # (r"/api/journey/publish"        , journey_publish_api.PublishHandler),# 未启用

            # 未知
            (r"/api/img/user/full/(\d+).jpg", img_api.UserFullHandler),
            (r"test", user_api.TestHandler),
            (r"file", user_api.FileHandler),

            # CMS
            (r"/api/app/updatefile", app_api.AppFileUpdateHandler),  # (后台运维使用)更新脚本文件及景点描述title信息
            (r"/api/app/updproductdesc", app_api.ProductDescUpdateHandler),  # (后台运维使用)更新特产描述title信息
            (r"/citymapupdate", city_update_api.CityMapUpdateHandler),
            # (后台运维使用)城市地图资源，及所有景点信息Json文件更新，成功后将更新城市基本信息中的version字段
            (r"/cityproductupdate", city_update_api.ProductUpdateHandler),  # (后台运维使用)城市所有特产信息Json文件更新
            (r"/citycardupdate", city_update_api.CardUpdateHandler),  # (后台运维使用)城市所有卡牌信息Json文件更新
            (r"/cityallupdate", city_update_api.AllUpdateHandler),  # (后台运维使用)城市所有信息一键更新
            (r'/cityadd', city_update_api.CityBaseAddHandler),
            (r'/cms/topic', manage_web.ManageTopicHandler),
            (r'/cms/topic/gallery', manage_web.ManageTopicGalleryHandler),  # 精选topic
            (r'/cms/topic/gallery/add', manage_web.TopicGalleryAddHandler),    # 增加精选
            (r'/cms/topic/gallery/refresh', manage_web.TopicGalleryRefreshHandler),   # 刷新精选
            (r'/cms/topic/note', manage_web.TopicNoteHandler),          # 管理note
            (r'/cms/topic/note/del', manage_web.TopicNoteDelHandler),   # 删除note
            (r'/cms/signin', manage_web.SigninHandler),   # CMS登录
            (r'/cms/signout', manage_web.SignoutHandler),   # CMS登出
            (r'/cms', manage_web.AuthHandler),   # CMS登录验证
            (r'/cms2/topic', manage_web2.ManageTopicHandler),
            (r'/cms2/topic/gallery', manage_web2.ManageTopicGalleryHandler),
            (r'/cms2/topic/gallery/get', manage_web2.GalleryHandler),
            (r'/cms2/topic/gallery/add', manage_web2.TopicGalleryAddHandler),    # 增加精选
            (r'/cms2/topic/gallery/refresh', manage_web2.TopicGalleryRefreshHandler),
            (r'/cms2/topic/note', manage_web2.TopicNoteHandler),          # 管理note
            (r'/cms2/topic/note/publish', manage_web2.TopicNotePubHandler),          # 管理note
            (r'/cms2/feedback', manage_web2.FeedbackHandler),
            (r'/cms2/user/fake', manage_web2.UserFakeHandler),
            (r'/cms2/user/normal', manage_web2.UserNormalHandler),
            (r'/cms2/user/black', manage_web2.UserBlackHandler),
            (r'/cms2/signin', manage_web2.SigninHandler),
            (r'/cms2/map/update', manage_web2.CityUpdateHandler),
            (r"/cms2/map/update/all", manage_web2.CityUpdateAllHandler),  # (后台运维使用)城市所有信息一键更新
            (r'/cms2/message/system', manage_web2.MessageSystemHandler),
            (r'/cms2/message/system/add', manage_web2.MessageSystemAddHandler),
            (r'/cms2/map/city/add', manage_web2.CityBaseAddHandler),

            (r'/cms/message/system/add', manage_message_api.AddSystemMessageHandler),
            (r'/cms/fakeuser/list', manage_fake_user_api.GetAllFakeUsersHandler),
            (r'/cms/fakeuser/add', manage_fake_user_api.AddFakeUserHandler),
            (r'/cms/fakeuser/update', manage_fake_user_api.UpdateOneFakeUserHandler),
            (r'/cms/feedback/list', manage_feedback_api.ListFeedbackHandler),
            (r'/cms/gallery/refresh', manage_gallery_api.TopicGalleryRefreshHandler),
            (r'/cms/gallery/add', manage_gallery_api.TopicGalleryAddHandler),
            (r'/cms/gallery/list', manage_gallery_api.GalleryHandler),
            (r'/cms/gallery/manage', manage_gallery_api.ManageTopicGalleryHandler),
            (r'/cms/note', manage_note_api.TopicNoteHandler),
            (r'/cms/note/del', manage_note_api.TopicNoteDelHandler),
            (r'/cms/note/post', manage_note_api.TopicNotePostHandler),
            (r'/cms/note/update', manage_note_api.UpdateTopicNoteHandler),
            (r'/cms/topic/add', manage_topic_api.AddTopicHandler),
            (r'/cms/topic/update', manage_topic_api.UpdateTopicHandler),

            (r'/cms/user/list', manage_user_api.GetAllUser),
            (r'/cms/blackuser/list', manage_user_api.GetAllBlackUser),
            (r'/cms/blackuser/mark', manage_user_api.MarkUserAsBlack),
            (r'/cms/blackuser/del', manage_user_api.MarkUserAsNormal),
            (r'/cms/user/update', manage_user_api.UpdateOneUserHandler),
            # (r'/cms/signin', manager_api.SigninHandler),
            # (r'/cms/signout', manager_api.SignoutHandler),


            ('.*', guest.PageNotFoundHandler),
        ]
        tornado.web.ErrorHandler = guest.PageNotFoundHandler
        tornado.web.Application.__init__(self, handlers, **settings)

        # data_img_base_mysql.create_img_base_table_if_not_exist()
        # data_user_base_mysql.create_user_base_table_if_not_exist()
        # data_user_info_mysql.create_user_info_table_if_not_exist()
        # data_user_ss_mysql.create_user_ss_table_if_not_exist()
        # data_city_mysql.create_city_base_table_if_not_exist()
        # data_collect_mysql.create_collect_item_table_if_not_exist()
        # data_img_base_mysql.create_img_base_table_if_not_exist()

        mongo.create_seq_userid(20000000)
        mongo.create_seq_resetid(10000000)
        mongo.create_seq_labelid(100000000)
        mongo.create_seq_imgid(100000000)
        mongo.create_seq_topicid(30000000)
        mongo.create_seq_noteid(40000000)
        # mongo.create_seq_messageid(50000000)


def main(p_port):
    if p_port == 0:
        print 'port could not be set as 0'
        log.e('port could not be set as 0')
        exit(1)
    log.c('www listening on port : %s' % p_port)
    app = Application()
    app.listen(p_port, xheaders=True)
    tornado.ioloop.IOLoop.instance().start()

# define("port", default=8888, help="run on the given port", type=int)
port = 0
try:
    port = int(sys.argv[1].split('=')[1])
except:
    print 'need port params'
    log.e('need port params')
    exit(1)

if __name__ == "__main__":
    main(port)
